#include "discovery/eventfd_domain_socket_receiver.h"
#include "discovery/eventfd_domain_socket_sender.h"
#include "discovery/eventfd_types.h"
#include "log/logger.h"
#include <boost/asio.hpp>
#include <sys/eventfd.h>
#include <unistd.h>

using namespace boost::asio;

// 使用示例
class EventFdTransferExamples {
public:
    // EventFD接收器示例
    static void run_receiver() {
        io_context io;
        
        EventFdDomainSocketReceiver receiver(io, "/tmp/eventfd_transfer_socket");
        
        // 设置扩展的EventFD接收回调（包含消息信息）
        receiver.set_extended_transfer_callback([](const boost::system::error_code& ec, int eventfd, const TransferMessage& msg) {
            if (!ec) {
                JC_INFO("接收器收到EventFD: {} 来自进程: {}", eventfd, msg.sender_pid);
                JC_INFO("消息类型: {}", msg.get_message_type());
                JC_INFO("主题名称: {}", msg.get_topic_name());
                JC_INFO("自定义数据: {}", msg.get_custom_data());
                JC_INFO("消息ID: {}, 优先级: {}, 标志: {}", msg.message_id, msg.priority, msg.flags);
                
                // 测试读取EventFD
                uint64_t value;
                ssize_t result = read(eventfd, &value, sizeof(value));
                if (result == sizeof(value)) {
                    JC_INFO("从EventFD读取到值: {}", value);
                }
                
                close(eventfd);
            } else {
                JC_ERROR("接收EventFD失败: {}", ec.message());
            }
        });

        boost::asio::steady_timer timer(io, std::chrono::seconds(6));
        std::function<void(const boost::system::error_code &)> timer_handler =
            [&receiver, &timer, &timer_handler](const boost::system::error_code &) {
              JC_INFO("接收器连接数: {}", receiver.connection_count());
              timer.expires_after(std::chrono::seconds(6));
              timer.async_wait(timer_handler);
            };
        timer.async_wait(timer_handler);
        
        if (receiver.start()) {
            JC_INFO("接收器启动成功");
            io.run();
        }
    }
    
    // EventFD发送器示例
    static void run_sender() {
        io_context io;
        
        EventFdDomainSocketSender sender(io, "/tmp/eventfd_transfer_socket");
        
        // 设置超时参数
        sender.set_timeouts(
            std::chrono::milliseconds(3000),  // 连接超时
            std::chrono::milliseconds(2000)   // 重试间隔
        );
        
        if (sender.start()) {
            JC_INFO("发送器启动成功");
            
            // 创建EventFD并发送（带扩展信息）
            int efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
            if (efd >= 0) {
                // 先向EventFD写入数据
                uint64_t value = 42;
                write(efd, &value, sizeof(value));
                JC_INFO("发送器写入EventFD: {}", value);
                
                // 异步发送带有扩展信息的EventFD
                sender.async_send_eventfd_with_info(
                    efd,
                    "sensor_data",              // 消息类型
                    "temperature_sensor_01",    // 主题名称
                    "温度: 25.6°C, 湿度: 60%",  // 自定义数据
                    12345,                      // 消息ID
                    1,                          // 优先级
                    0x01,                       // 标志
                    [efd](const boost::system::error_code& ec, int sent_fd) {
                        if (!ec) {
                            JC_INFO("发送器成功发送EventFD: {} (带扩展信息)", sent_fd);
                        } else {
                            JC_ERROR("发送EventFD失败: {}", ec.message());
                        }
                    }
                );
            }
            
            // 运行一段时间后退出
            steady_timer timer(io, std::chrono::seconds(10));
            timer.async_wait([&io](const boost::system::error_code&) {
                io.stop();
            });
            
            io.run();
        }
        JC_INFO("发送器退出");
    }
};

// 主函数示例
int main(int argc, char* argv[]) {
    if (argc > 1) {
        std::string mode = argv[1];
        if (mode == "receiver") {
            EventFdTransferExamples::run_receiver();
        } else if (mode == "sender") {
            EventFdTransferExamples::run_sender();
        } else {
            JC_INFO("用法: {} [receiver|sender]", argv[0]);
        }
    } else {
        JC_INFO("用法: {} [receiver|sender]", argv[0]);
        EventFdTransferExamples::run_sender();
    }
    
    return 0;
}
